import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
//axios配置
//放到线上
const http = axios.create({
	baseURL: process.env.NODE_ENV === 'production' ? '' : '/web',
	timeout: 30000
})

//request 请求拦截器，post传参序列化
// 每次请求都为http头增加Authorization字段，其内容为Token
http.interceptors.request.use(
	config => {
		const method = config.method;
		const token = localStorage.getItem('access_token')
		if(token) {
			config.headers.common['Authorization'] = 'Bearer ' + token
		}


		if(method === 'post' || method === 'put' || method === 'delete') {
			config.data = qs.stringify(config.data)
		}
		
		return config
	}, error => {
		return Promise.reject(error)
	}
)

//response 拦截,响应数据操作
http.interceptors.response.use((res) => {
	if(res.status !== 200) {
		return Promise.reject(res)
	}
	return res
}, (error) => {
	//404,401等问题可以在这里处理
	console.log(error.response, 555)
	if(401 !== error.response.status) {
		let resData = error.response.data;
		let message = resData.msg
		Message({
			message: message,
			type: 'error',
			duration: 3 * 1000
		})
	} else if(401 === error.response.status) {
		localStorage.clear()
		window.location.href = '#/login'
	} else {
		!error.__CANCEL__ && Message({
			message: '网络异常',
			type: 'error',
			duration: 3 * 1000
		});
		
	}
	return Promise.reject(error);
});

export default http